import 'dart:convert';
import 'dart:math';
import 'package:injectable/injectable.dart';
import 'package:vista/shared/models/challenge_submission.dart';
import 'package:vista/shared/models/like_frame.dart';
import 'package:vista/shared/models/theme_challenge.dart';
import 'package:vista/shared/services/storage_service.dart';
import 'package:vista/shared/services/auth_focus.dart';

/// 主题挑战服务
/// 处理主题挑战的创建、投稿管理，如摄影挑战般组织活动
@lazySingleton
class ThemeChallengeService {
  final StorageService _storageService;
  final AuthFocus _authFocus;
  static const String _challengesKey = 'theme_challenges';
  static const String _submissionsKey = 'challenge_submissions';
  static const String _isInitializedKey = 'theme_challenges_initialized';
  static const String _likesPrefix = 'submission_likes_';

  ThemeChallengeService(this._storageService, this._authFocus);

  /// 初始化默认主题挑战数据
  /// 创建一个默认主题和6条投稿数据
  Future<void> initializeDefaultChallenges() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    final users = await _authFocus.getUsers();
    if (users.isEmpty) {
      return;
    }

    final now = DateTime.now();
    final defaultChallenges = <ThemeChallenge>[];
    final defaultSubmissions = <ChallengeSubmission>[];

    // 创建一个默认主题
    final challengeId = 'challenge_${now.millisecondsSinceEpoch}';
    defaultChallenges.add(
      ThemeChallenge(
        id: challengeId,
        title: 'Golden Hour Photography',
        description:
            'Capture the magic of golden hour - the warm, soft light that transforms ordinary scenes into extraordinary moments.',
        coverImage: 'assets/images/group1.png',
        createdAt: now.subtract(const Duration(days: 7)),
      ),
    );

    // 创建6条默认投稿数据
    final authors = users.take(6).toList();
    for (int i = 0; i < 6 && i < authors.length; i++) {
      final author = authors[i];
      final submissionId = 'submission_${now.millisecondsSinceEpoch}_$i';

      defaultSubmissions.add(
        ChallengeSubmission(
          id: submissionId,
          challengeId: challengeId,
          authorId: author.id,
          image: 'assets/images/daily${(i % 10) + 1}.png',
          viewCount: _getRandomViewCount(),
          timestamp: now.subtract(Duration(days: 6 - i, hours: i * 3)),
        ),
      );
    }

    // 保存所有数据
    await _saveChallenges(defaultChallenges);
    await _saveSubmissions(defaultSubmissions);
    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 保存主题列表
  Future<void> _saveChallenges(List<ThemeChallenge> challenges) async {
    final challengesJson = challenges.map((c) => c.toJson()).toList();
    final challengesString = jsonEncode(challengesJson);
    await _storageService.persistString(_challengesKey, challengesString);
  }

  /// 保存投稿列表
  Future<void> _saveSubmissions(List<ChallengeSubmission> submissions) async {
    final submissionsJson = submissions.map((s) => s.toJson()).toList();
    final submissionsString = jsonEncode(submissionsJson);
    await _storageService.persistString(_submissionsKey, submissionsString);
  }

  /// 获取所有主题
  Future<List<ThemeChallenge>> getAllChallenges() async {
    final challengesString = await _storageService.retrieveString(
      _challengesKey,
    );
    if (challengesString == null) {
      return [];
    }

    try {
      final List<dynamic> challengesJson = jsonDecode(challengesString);
      return challengesJson
          .map((json) => ThemeChallenge.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
    } catch (e) {
      return [];
    }
  }

  /// 根据ID获取主题
  Future<ThemeChallenge?> getChallengeById(String challengeId) async {
    final challenges = await getAllChallenges();
    try {
      return challenges.firstWhere((c) => c.id == challengeId);
    } catch (e) {
      return null;
    }
  }

  /// 获取当前活跃的主题（暂时只有一个）
  Future<ThemeChallenge?> getCurrentChallenge() async {
    final challenges = await getAllChallenges();
    if (challenges.isEmpty) {
      return null;
    }
    // 返回最新的主题
    return challenges.first;
  }

  /// 获取主题下的所有投稿
  Future<List<ChallengeSubmission>> getSubmissionsByChallenge(
    String challengeId,
  ) async {
    final submissionsString = await _storageService.retrieveString(
      _submissionsKey,
    );
    if (submissionsString == null) {
      return [];
    }

    try {
      final List<dynamic> submissionsJson = jsonDecode(submissionsString);
      final allSubmissions =
          submissionsJson
              .map(
                (json) =>
                    ChallengeSubmission.fromJson(json as Map<String, dynamic>),
              )
              .toList();

      return allSubmissions.where((s) => s.challengeId == challengeId).toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 根据用户ID获取投稿
  Future<List<ChallengeSubmission>> getSubmissionsByUser(String userId) async {
    final submissionsString = await _storageService.retrieveString(
      _submissionsKey,
    );
    if (submissionsString == null) {
      return [];
    }

    try {
      final List<dynamic> submissionsJson = jsonDecode(submissionsString);
      final allSubmissions =
          submissionsJson
              .map(
                (json) =>
                    ChallengeSubmission.fromJson(json as Map<String, dynamic>),
              )
              .toList();

      return allSubmissions.where((s) => s.authorId == userId).toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 发布投稿
  Future<ChallengeSubmission> submitChallenge({
    required String challengeId,
    required String authorId,
    required String image,
  }) async {
    final submission = ChallengeSubmission(
      id: 'submission_${DateTime.now().millisecondsSinceEpoch}',
      challengeId: challengeId,
      authorId: authorId,
      image: image,
      timestamp: DateTime.now(),
    );

    final submissionsString = await _storageService.retrieveString(
      _submissionsKey,
    );
    List<ChallengeSubmission> allSubmissions = [];

    if (submissionsString != null) {
      try {
        final List<dynamic> submissionsJson = jsonDecode(submissionsString);
        allSubmissions =
            submissionsJson
                .map(
                  (json) => ChallengeSubmission.fromJson(
                    json as Map<String, dynamic>,
                  ),
                )
                .toList();
      } catch (e) {
        // 如果解析失败，使用空列表
      }
    }

    allSubmissions.insert(0, submission);
    await _saveSubmissions(allSubmissions);

    return submission;
  }

  /// 创建新主题
  Future<ThemeChallenge> createChallenge({
    required String title,
    required String description,
    required String coverImage,
  }) async {
    final challenge = ThemeChallenge(
      id: 'challenge_${DateTime.now().millisecondsSinceEpoch}',
      title: title,
      description: description,
      coverImage: coverImage,
      createdAt: DateTime.now(),
    );

    final challenges = await getAllChallenges();
    challenges.insert(0, challenge);
    await _saveChallenges(challenges);

    return challenge;
  }

  /// 获取随机访问次数（50-500之间）
  int _getRandomViewCount() {
    final random = Random();
    return 50 + random.nextInt(451); // 50到500之间的随机数
  }

  /// 增加投稿的访问次数
  Future<void> incrementViewCount(String submissionId) async {
    final submissions = await getAllSubmissions();
    final submission = submissions.firstWhere(
      (s) => s.id == submissionId,
      orElse: () => submissions.first,
    );

    final updatedSubmission = ChallengeSubmission(
      id: submission.id,
      challengeId: submission.challengeId,
      authorId: submission.authorId,
      image: submission.image,
      viewCount: submission.viewCount + 1,
      timestamp: submission.timestamp,
    );

    final index = submissions.indexWhere((s) => s.id == submissionId);
    if (index != -1) {
      submissions[index] = updatedSubmission;
      await _saveSubmissions(submissions);
    }
  }

  /// 获取所有投稿
  Future<List<ChallengeSubmission>> getAllSubmissions() async {
    final submissionsString = await _storageService.retrieveString(
      _submissionsKey,
    );
    if (submissionsString == null) {
      return [];
    }

    try {
      final List<dynamic> submissionsJson = jsonDecode(submissionsString);
      return submissionsJson
          .map(
            (json) =>
                ChallengeSubmission.fromJson(json as Map<String, dynamic>),
          )
          .toList();
    } catch (e) {
      return [];
    }
  }

  /// 获取投稿的点赞列表
  Future<List<LikeFrame>> getLikes(String submissionId) async {
    final key = '$_likesPrefix$submissionId';
    final likesString = await _storageService.retrieveString(key);
    if (likesString == null) {
      return [];
    }
    try {
      final List<dynamic> likesJson = jsonDecode(likesString);
      return likesJson
          .map((json) => LikeFrame.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 获取投稿的点赞数量
  Future<int> getLikeCount(String submissionId) async {
    final likes = await getLikes(submissionId);
    return likes.length;
  }

  /// 检查用户是否已点赞投稿
  Future<bool> isLiked(String submissionId, String userId) async {
    final likes = await getLikes(submissionId);
    return likes.any((like) => like.userId == userId);
  }

  /// 点赞投稿
  Future<void> likeSubmission(String submissionId, String userId) async {
    if (await isLiked(submissionId, userId)) {
      return; // 已经点赞过了
    }

    final likes = await getLikes(submissionId);
    likes.add(
      LikeFrame(
        id:
            'submission_like_${DateTime.now().millisecondsSinceEpoch}_$submissionId',
        postId: submissionId, // 复用LikeFrame，使用postId字段存储submissionId
        userId: userId,
        timestamp: DateTime.now(),
      ),
    );

    final key = '$_likesPrefix$submissionId';
    final likesJson = likes.map((like) => like.toJson()).toList();
    final likesString = jsonEncode(likesJson);
    await _storageService.persistString(key, likesString);
  }

  /// 取消点赞投稿
  Future<void> unlikeSubmission(String submissionId, String userId) async {
    final likes = await getLikes(submissionId);
    likes.removeWhere((like) => like.userId == userId);

    final key = '$_likesPrefix$submissionId';
    if (likes.isEmpty) {
      await _storageService.removeKey(key);
    } else {
      final likesJson = likes.map((like) => like.toJson()).toList();
      final likesString = jsonEncode(likesJson);
      await _storageService.persistString(key, likesString);
    }
  }

  /// 删除投稿
  Future<void> deleteSubmission(String submissionId) async {
    final allSubmissions = await getAllSubmissions();
    allSubmissions.removeWhere((submission) => submission.id == submissionId);
    await _saveSubmissions(allSubmissions);

    // 同时删除相关的点赞
    final likesKey = '$_likesPrefix$submissionId';
    await _storageService.removeKey(likesKey);
  }
}
